package cn.flexui.flexuiserver.controller.web;

import cn.flexui.flexuiserver.config.properties.StripeProperties;
import cn.flexui.flexuiserver.service.PaymentInfoService;
import com.stripe.exception.SignatureVerificationException;
import com.stripe.model.Event;
import com.stripe.model.EventDataObjectDeserializer;
import com.stripe.model.PaymentIntent;
import com.stripe.net.Webhook;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RequestMapping("/stripe")
@RestController
public class StripeWebhookController {


    @Autowired
    private StripeProperties stripeProperties;
    @Autowired
    private PaymentInfoService paymentInfoService;


    @PostMapping("/webhook")
    public String handleStripeEvent(@RequestBody String payload,
                                    @RequestHeader("Stripe-Signature") String sigHeader) {

        try {
            Event event;

            log.info("handleStripeEvent payload: {}", payload);
            try {
                event = Webhook.constructEvent(payload, sigHeader, stripeProperties.getWebhookSecret());
            } catch (SignatureVerificationException e) {
                return "Invalid signature";
            }

            EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer();

            if ("payment_intent.succeeded".equals(event.getType())) {
                PaymentIntent paymentIntent = (PaymentIntent) dataObjectDeserializer.getObject().orElseThrow();
                paymentInfoService.handleSuccessfulPayment(paymentIntent);
            } else if ("payment_intent.payment_failed".equals(event.getType())) {
                PaymentIntent paymentIntent = (PaymentIntent) dataObjectDeserializer.getObject().orElseThrow();
                paymentInfoService.handleFailedPayment(paymentIntent);
            } else {
                log.info("此类型:{} 不处理", event.getType());
            }
            return "Received";
        } catch (Exception e) {
            log.error("webhook支付通知异常", e);
        }

        return "Invalid signature";

    }

}
